/**
 * salesflow.jsp引用
 * @param $
 * @param win
 * @param doc
 */
var url = '/business/salesFlowServlet';
(function($, win, doc){
	// 查询条件
	var getClerks = function(){
		$.ajax({
	        url: CONTEXT_PATH + '/ktcount/getClerks', //localhost:8080
	        data:{"shopId":$('#shop').combobox('getValue')},
	        type: 'post',
	        success: function (data) {
	           	var data = data.data;
	           	$('#cashier').combobox("loadData",data);
	        },
	        error: function (error) {
	            alert(error)
	        }
	    })
	}
	var createCondCombox = function(){
		// 分店
		param = Param.getReadCmd();
		param[Param.CMDTYPEKEY] = 1;
		param[Param.CMDVALUEKEY] = 1;
		var cond = {};
		param = Param.buildParam(param,cond);
		var param = {
            	shopType:"",
				zoneCode:''
		}
/*		$('#shop').combobox({
			url: CONTEXT_PATH + '/ktcount/getShops',
			queryParams : param,
			method : 'post',
		    valueField: 'shopId',
		    textField: 'shopName',
		    loader: Util.combox.loader,
		    onClick: function(node) { 
                attributeShow($("#shop").combotree("getValue")); 
            }, 
            filter: function(q, row){ 
                var opts = $(this).combobox('options'); 
                //return row[opts.textField].indexOf(q) == 0; 
                return row[opts.textField].indexOf(q)>-1;//将从头位置匹配改为任意匹配 
            }, 
            onLoadSuccess: function (val) {  //下拉框数据加载成功调用
            	//如果只有一个店铺就默认选中这个店铺
	           	 var data = val["data"];
	           	 $('#shop').combobox("loadData",data);
            }
		});*/
		$.ajax({
	        url: CONTEXT_PATH + '/ktcount/getShops', //localhost:8080
	        data:{"zoneCode":"","shopType":"\'中深\'"},
	        type: 'post',
	        success: function (data) {
	           	var data = data.data;
	           	if(data.length == 0)
	           		return;
	           	$('#shop').combobox({onSelect:function(record){
	           		getClerks();
	           		}
	           	});
	           	$('#shop').combobox("loadData",data).combobox("select",data[0]["shopId"])
	           	onQuery();
	           	getClerks();
	        },
	        error: function (error) {
	            alert(error)
	        }
	    })
		// 供应商
		param = Param.getReadCmd();
		param[Param.CMDTYPEKEY] = 3;
		param[Param.CMDVALUEKEY] = 1;
		var cond = {};
		param = Param.buildParam(param,cond);
		$('#supplier').combobox({
			url: CONTEXT_PATH + '/ktcount/getSupplier',
			queryParams : param,
			method : 'post',
		    valueField: 'ID',
		    textField: 'NAME',
		    multiple:true,
		    loader: Util.combox.loader,
		    filter: function(q, row){ 
                var opts = $(this).combobox('options'); 
                //return row[opts.textField].indexOf(q) == 0; 
                return row[opts.textField].indexOf(q)>-1;//将从头位置匹配改为任意匹配 
            }, 
		    formatter: function (row) {
                var opts = $('#supplier').combobox('options');
                return '<input type="checkbox" class="combobox-checkbox">' + row[opts.textField]
            },
            onLoadSuccess: function () {  //下拉框数据加载成功调用
                var opts = $('#supplier').combobox('options');
                var target = this;
                var values = $(target).combobox('getValues');//获取选中的值的values
                $.map(values, function (value) {
                    var el = opts.finder.getEl(target, value);
                    el.find('input.combobox-checkbox')._propAttr('checked', true); 
                })
            },
            onSelect: function (row) { //选中一个选项时调用
                var opts = $('#supplier').combobox('options');
                //获取选中的值的values
                $("#supplier").val($('#supplier').combobox('getValues'));
			   //设置选中值所对应的复选框为选中状态
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', true);
            },
            onUnselect: function (row) {//不选中一个选项时调用
                var opts = $('#supplier').combobox('options');
                //获取选中的值的values
                $("#supplier").val($('#supplier').combobox('getValues'));
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', false);
            }
		});
		// 品牌
		param = Param.getReadCmd();
		param[Param.CMDTYPEKEY] = 4;
		param[Param.CMDVALUEKEY] = 1;
		var cond = {};
		param = Param.buildParam(param,cond);
		$('#brand').combobox({
			url: CONTEXT_PATH + '/ktcount/getBrand',
			queryParams : param,
			method : 'post',
		    valueField: 'ID',
		    textField: 'NAME',
		    multiple:true,
		    loader: Util.combox.loader,
		    filter: function(q, row){ 
                var opts = $(this).combobox('options'); 
                //return row[opts.textField].indexOf(q) == 0; 
                return row[opts.textField].indexOf(q)>-1;//将从头位置匹配改为任意匹配 
            }, 
		    formatter: function (row) {
                var opts = $('#brand').combobox('options');
                return '<input type="checkbox" class="combobox-checkbox">' + row[opts.textField]
            },
            onLoadSuccess: function () {  //下拉框数据加载成功调用
                var opts = $('#brand').combobox('options');
                var target = this;
                var values = $(target).combobox('getValues');//获取选中的值的values
                $.map(values, function (value) {
                    var el = opts.finder.getEl(target, value);
                    el.find('input.combobox-checkbox')._propAttr('checked', true); 
                })
            },
            onSelect: function (row) { //选中一个选项时调用
                var opts = $('#brand').combobox('options');
                //获取选中的值的values
                $("#brand").val($('#brand').combobox('getValues'));
			   //设置选中值所对应的复选框为选中状态
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', true);
            },
            onUnselect: function (row) {//不选中一个选项时调用
                var opts = $('#brand').combobox('options');
                //获取选中的值的values
                $("#brand").val($('#brand').combobox('getValues'));
                var el = opts.finder.getEl(this, row[opts.valueField]);
                el.find('input.combobox-checkbox')._propAttr('checked', false);
            }
		});
	};
	/**
	 * 创建条件对象
	 */
	var getCond2 = function(){
		var cond = {};
		//区域
		//var area = $('#area').combobox('getValue');
		var area = $('#areaCode').val();
		cond['ZONE_CODE'] = Param.buildParamItem('IN', area, Param.SQLType.VARCHAR); 
		return cond;
	}
	var getCond = function() {
		var cond = {};
		// 时间
		var startTime = $('#startTime').datebox('getValue');
		cond['startTime'] = Param.buildParamItem('=', startTime, Param.SQLType.VARCHAR); 
		var endTime = $('#endTime').datebox('getValue');
		cond['endTime'] = Param.buildParamItem('=', endTime, Param.SQLType.VARCHAR); 
		//区域
		var area = $('#area').combobox('getValue');
		cond['area'] = Param.buildParamItem('=', area, Param.SQLType.VARCHAR); 
		//分店
		var shop = $('#shop').combobox('getValue');
		cond['shop'] = Param.buildParamItem('=', shop, Param.SQLType.VARCHAR); 
		//商品类型
		var goodsType = $('#goodsType').combobox('getValue');
		cond['goodsType'] = Param.buildParamItem('=', goodsType, Param.SQLType.VARCHAR); 
		//品牌
//		var brand = $('#brand').combobox('getValue');
//		cond['brand'] = Param.buildParamItem('=', brand, Param.SQLType.VARCHAR); 
		//供应商
		var supplier = $('#supplier').combobox('getValue');
		cond['supplier'] = Param.buildParamItem('=', supplier, Param.SQLType.VARCHAR); 
		//收银员
		var cashier = $('#cashier').val();
		if(cashier==""){
			cashier = "-";
		}
		cond['cashier'] = Param.buildParamItem('=', '%'+cashier+'%', Param.SQLType.VARCHAR); 

		//会员卡号
		var card = $('#card').val();
		if(card==""){
			card = "-";
		}
		cond['card'] = Param.buildParamItem('=', '%'+card+'%', Param.SQLType.VARCHAR); 
		//批次号
		var batchNo = $('#batchNo').val();
		if(batchNo==""){
			batchNo = "-";
		}
		cond['batchNo'] = Param.buildParamItem('=', '%'+batchNo+'%', Param.SQLType.VARCHAR); 
		//单号
		var dNum = $('#dNum').val();
		if(dNum==""){
			dNum = "-";
		}
		cond['dNum'] = Param.buildParamItem('=', '%'+dNum+'%', Param.SQLType.VARCHAR); 
		//货号
		var artNo = $('#artNo').val();
		if(artNo==""){
			artNo = "-";
		}
		cond['artNo'] = Param.buildParamItem('=', '%'+artNo+'%', Param.SQLType.VARCHAR); 
		//商品名称
		var goodsName = $('#goodsName').val();
		if(goodsName==""){
			goodsName = "-";
		}
		cond['goodsName'] = Param.buildParamItem('=', '%'+goodsName+'%', Param.SQLType.VARCHAR); 
		return cond;
	};
	// 查询
	var onQuery = function(){
		var cond = getCond();
		if(!Util.nvl(cond) && cond == false){
			return ;
		}
		var param = Param.getReadCmd();
		param = Param.buildParam(param, cond);
		
		//获取参数
		var startTime = $('#startTime').datebox('getValue');
		var endTime = $('#endTime').datebox('getValue');
		var areaCode = $('#areaCode').val();
		var shopIds = $('#shop').combobox('getValues');
			shopIds = shopIds.toString()== "" ?"\'\'":shopIds.toString();
		var goodsTypeId = $('#goodsTypeId').val();
		var goodsType = $('#goodsType').combobox('getValues').toString();
//		var brandIds = $('#brand').combobox('getValues').toString();
		var supplier = $('#supplier').combobox('getValue');
		var shortCode = $('#shortCode').val();
		var salesMethod = $('#salesMethod').val();
		var benefitType = $('#benefitType').val();
		var cashier = $('#cashier').combobox('getValue');
		var pos = $('#pos').val();
		var card = $('#card').val();
		var batchNo = $('#batchNo').val();
		var dNum = $('#dNum').val();
		var artNo = $('#artNo').val();
		var goodsName = $('#goodsName').val();
		var params = {
			startTime:startTime,
			endTime:endTime,
			areaCode:areaCode,
			shopIds:shopIds,
			goodsType:goodsType,
			goodsTypeId:goodsTypeId,
//			brandIds:brandIds,
			supplier:supplier,
			shortCode:shortCode,
			salesMethod:salesMethod,
			benefitType:benefitType,
			cashier:cashier,
			pos:pos,
			card:card,
			batchNo:batchNo,
			dNum:dNum,
			artNo:artNo,
			goodsName:goodsName,
            shopType:"'中深'",
		};
		$('#dg').datagrid({
			url: CONTEXT_PATH +'/ktcount/salesFlowList',
			queryParams: params,
			method: 'POST'
		});
	};
	// 导出excel
	var onExpExcel = function() {
		var cond = getCond();
		if (!cond) {
			return false;
		}
		var param = Param.getExportCmd();
		param = Param.buildParam(param, cond);
		Util.doPost(url, param, function(data) {
			if (data && data.file) {
				win.open(data.file);
			} else if (data && data.stateMsg) {
				Util.msg.alert(data.stateMsg);
				return false;
			}
		});
	};
   var easyuiExportToExcel = function(){ 
	   var startTime = $('#startTime').datebox('getValue');	
	   var endTime = $('#endTime').datebox('getValue');	
	   var shop = $('#shop').combobox('getText');
	   var area = $('#area').combobox('getText');
  	   //exportExcel.jqgridtoExcel($(".datagrid-header"),$(".datagrid-body"),'贵州科泰易购商贸有限公司 销售流水报表',startTime,endTime,area,shop);
  	   $('#dg').tableExport({type:'xls',fileName:'销售流水表',tableName:'销售流水表',AREA:area,SHOP:shop,START_TIME:startTime,END_TIME:endTime});
   }
	//区域树状
	var getArea = function(){
		 var setting = {
	                view: {
	                    dblClickExpand: false,
	                    showLine: true,
	                    selectedMulti: false
	                }, 
	                check: {
                     enable: true,
                     chkStyle: "checkbox",
                 },
	                data: {
	                    simpleData: {
	                        enable: true,
	                        idKey: "ZONE_CODE",
	                        pIdKey: "PARENT_ID",
	                        rootPId: '',
	                        areaCode:"ZONE_CODE"
	                    },
	    				key: {
	                        name: 'ZONE_NAME'
	    				}
	                },
	                callback: { //回调函数
	    				  onDblClick: function (treeId, treeNode) {
	    					  
	    					  var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	    					  var node = treeObj.getSelectedNodes();//点击节点后 获取节点数据
	                       // $("#area").val(node[0].text)
	                        $('#area').combobox('setValue', node[0].text);
	                        $("#typeId").val(node[0].tId)
	                        layer.close(modalIndex)
	    				  }
	                }
	            }
	        
			var param = Param.getReadCmd();
			var cond = {};
			param = Param.buildParam(param,cond);
			param[Param.CMDTYPEKEY] = 0;
			param[Param.CMDVALUEKEY] = 1;
			param = {
					zoneCode:'',
					state:1
			}
	        $.ajax({
	        	url: CONTEXT_PATH + '/ktcount/getAreas',
				//data : param,
	            type : "post",
	            dataType : "json",
	            async : false,
	            success : function(data) {
	                var dataArray = data.data;
	                $.fn.zTree.init($("#treeDemo"), setting, dataArray);
	                $("#authorizationInfoContentBrodBrand").removeClass("hide");
	            },
	            error : function () {
	                layer.closeAll('loading');
	                layer.msg("网络异常")
	            }
	        });
	}
	 //区域确定
	 var areaButton = function(){
		 var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
		 var nodes = treeObj.getCheckedNodes();
	     var areaNameVal = "",areaCodeVal = "";
	     for(var i = 0,nodesLen = nodes.length;i < nodesLen;i++){
//	    	 if(!nodes[i]["isParent"]){
	    		 areaNameVal += nodes[i]["ZONE_NAME"]+",";
		    	 areaCodeVal += nodes[i]["ZONE_CODE"]+",";
//	    	 }
	     }
	     if(nodes.length > 0){
	    	 areaNameVal = areaNameVal.substring(0,areaNameVal.length-1);
	    	 areaCodeVal = areaCodeVal.substring(0,areaCodeVal.length-1);
	     }
	     if(nodes.length == 0){
	    	 $('#area').combobox('setValue', '-');
	     }else{
	    	 $('#area').combobox('setValue', areaNameVal);
	     }
	     
	     $('#areaCode').val(areaCodeVal);
	     $('#areaWindow').window('close');
	     var cond = getCond2();
	     var param = Param.getReadCmd();
			param[Param.CMDTYPEKEY] = 1;
			param[Param.CMDVALUEKEY] = 1;
			param = Param.buildParam(param,cond);
			var param = {
                shopType:"'中深'",
				zoneCode:$("#areaCode").val()
			}
			$('#shop').combobox({
				url: CONTEXT_PATH + '/ktcount/getShop',
				queryParams : param,
				method : 'post',
			    valueField: 'SHOP_ID',
			    textField: 'SHOP_NAME',
			    loader: Util.combox.loader
			}).combobox('setValue', '-');
		  
	 }
	 var areaTree = function(){
		 $('#areaWindow').dialog('open');
	 }
	 
	 //商品类型树状
	 var goodsTypeTd = function(){
		 var setting = {
	                view: {
	                    dblClickExpand: false,
	                    showLine: true,
	                    selectedMulti: false
	                }, 
	                check: {
                     enable: true,
                     chkStyle: "checkbox",
                 },
                 data: {
                     simpleData: {
                         enable: true,
                         idKey: "TYPE_ID",
                         pIdKey: "PARENT_ID",
                         rootPId: '',
                         typeId:"TYPE_ID"
                     },
     				key: {
                         name: 'TYPE_NAME'
     				}
                 },
	            }	        
	        	var filters = {
	                "rules": [
	                    {
	                        "field": "state",
	                        "data": '1'
	                    }
	                ]
	            };
	            var queryModels = {
	                page: '1',
	                rows: '10000',
	                filters: JSON.stringify(filters), 
	            };
	            var param = Param.getReadCmd();
				var cond1 = {};
				param = Param.buildParam(param,cond1);
				param[Param.CMDTYPEKEY] = 2;
				param[Param.CMDVALUEKEY] = 1;
	        $.ajax({
	        	url: CONTEXT_PATH + '/ktcount/getGoodsType',
				data : param,
	            type : "get",
	            dataType : "json",
	            async : false,
	            success : function(data) {
	                var dataArray = data;
	                $.fn.zTree.init($("#treeDemo2"), setting, dataArray);
	                $("#authorizationInfoContentBrodBrand").removeClass("hide");
	            },
	            error : function () {
	                layer.closeAll('loading');
	                layer.msg("网络异常")
	            }
	        });
	 }
	 //商品类型确定
	 var goodsTypeButton = function(){
		 var treeObj = $.fn.zTree.getZTreeObj("treeDemo2");
		 var nodes = treeObj.getCheckedNodes();
	     var typeNameVal = "",typeIdVal = "";
	     for(var i = 0,nodesLen = nodes.length;i < nodesLen;i++){
	    	 if(!nodes[i]["isParent"]){
	    		 typeNameVal += nodes[i]["TYPE_NAME"]+",";
		    	 typeIdVal += nodes[i]["TYPE_ID"]+",";
	    	 }
	     }
	     if(nodes.length > 0){
	    	 typeNameVal = typeNameVal.substring(0,typeNameVal.length-1);
	    	 typeIdVal = typeIdVal.substring(0,typeIdVal.length-1);
	     }
	     if(nodes.length = 0){
	    	 $('#goodsType').combobox('setValue', '-');
	     }else{
	    	 $('#goodsType').combobox('setValue', typeNameVal);
	     }
	     $('#goodsTypeId').val(typeIdVal);
	     $('#goodsTypeWindow').window('close');
	 }
	 var goodsTypeWin =  function(){
		 $("#goodsTypeWindow").dialog("open");
	 }
	 //清除shop输入框
	 var clearShop = function(){
		 $("#shop").combobox("clear");
	 }
	 //清除brand输入
	 var clearBrand = function(){
		 $("#brand").combobox("clear");
	 }
	 //清楚共供应商输入框
	 var supplierChange = function(){
		 $('#supplier').combobox('clear');
	 }
	// 初始化
	$(function(){
		$('#dg').datagrid({
			fit: true,
			showFooter:true,
            onLoadSuccess: compute,//页面刷新的时候触发求和的函数
            frozenColumns:[[{field: '_rn',title: '笔数',align: 'center',width: 30},
	    {field: 'OPERATOR_TIME',title: '销售时间',width: 120,align:'center',
		    formatter:function(val){
		    	if(val == undefined){
		    		return '';
		    	}else{
		    		return jsonTimeStamp(val.time);
		    	}
		    }	
	    },
	    {field: 'SHORT_CODE',title: '简码',width: 160,align:'center'},
	    {field: 'PRODUCT_NAME',title: '品名',width: 160,align:'center'},
	    {field: 'QUANTITY',title: '数量',width: 60,align:'center'},
	    {field: 'PRICE',title: '销售价格',width: 60,align:'center'},
	    {field: 'SALES_AMOUNT',title: '销售(实收)金额',width: 100,align:'center'},
	    {field: 'OPERATOR_NAME',title: '收营员',width: 70,align:'center'}
	    ]],
			columns: [[
			    {field: 'ORDER_ID',title: '单号',width: 160,align:'center'},
			    {field: 'TRAN_TYPE',title: '支付方式',width: 60,align:'center',
				    formatter:function(val){
				    	var res = '';
				    	if(val == '1'){
				    		res = '农行微信主扫';
				    	}else if(val == '2'){
				    		res = '农行微信被扫';
				    	}else if(val == '5'){
				    		res = '银联在线';
				    	}else if(val == '6'){
				    		res = 'pos支付';
				    	}else if(val == '7'){
				    		res = '现金支付';
				    	}else if(val == '8'){
				    		res = 'pos优惠';
				    	}else if(val == '9'){
				    		res = '原生微信';
				    	}else if(val == '10'){
				    		res = '原生支付宝';
				    	}else if(val == '11'){
				    		res = '商户微信';
				    	}else if(val == '12'){
				    		res = '商户支付宝';
				    	}
				    	return res;
				    }	
				    },
			    {field: 'SHOP_NAME',title: '仓库名称',width: 100,align:'center'},
			    {field: 'PRODUCT_CODE',title: '货号',width: 100,align:'center'},
			    {field: 'UNIT',title: '单位',width: 40,align:'center'},
			    {field: 'SPEC',title: '规格',width: 70,align:'center'},
			    {field: 'CST_PRICE',title: '进价',width: 60,align:'center'},
			    {field: 'RTL_PRICE',title: '原价',width: 60,align:'center'},
			    {field: 'RTL_PRICE_AMOUNT',title: '原价金额',width: 60,align:'center'},
			    {field: 'CST_PRICE_AMOUNT',title: '进价金额',width: 60,align:'center'},
			    {field: 'SELF_CODE',title: '自编码',width: 60,align:'center'},
			    {field: 'PRODUCT_TYPE_ID',title: '类别编码',width: 60,align:'center'},
			    {field: 'TYPE_NAME',title: '类别名称',width: 80,align:'center'},
			    {field: 'BRAND_ID',title: '品牌编码',width: 60,align:'center'},
			    {field: 'BRAND_NAME',title: '品牌名称',width: 60,align:'center'},
			    {field: 'CUSTOMER_ID',title: '会员ID',width: 60,align:'center'},
			    {field: 'CUSTOMER_MOBILE',title: '会员卡号',width: 60,align:'center'},
			    {field: 'CUSTOMER_NAME',title: '会员名称',width: 60,align:'center'},
			    {field: 'OPERATOR_ID',title: '收银员编号',width: 70,align:'center'},
			    {field: 'REMARK',title: '退货原因',width: 60,align:'center'},
			    {field: 'STATE_TIME',title: '退货时间',width: 60,align:'center',
				    formatter:function(val){
				    	if(val == undefined){
				    		return '';
				    	}else{
				    		return jsonTimeStamp(val.time);
				    	}
				    }
			    },
			    {field: 'BENEFIT_AMT',title: '折扣',width: 60,align:'center'},
			    {field: 'BENEFIT_TYPE',title: '折扣类型',width: 60,align:'center'},
			    {field: 'SUPPLIER_ID',title: '供应商编号',width: 70,align:'center'},
			    {field: 'SUPPLIER_NAME',title: '供应商名称',width: 70,align:'center'},
			    {field: '_d',title: '备注',width: 60,align:'center'},
//			    {field: 'ORDER_ID',title: '原单号',width: 160,align:'center',hidden:true},
			    {field: '_b',title: '促销编号',width: 60,align:'center'},
			    {field: '_j',title: '券号',width: 60,align:'center'}
			]]
		});
		//创建条件查询下拉组件
		createCondCombox();
		// 初始化时间
		var cdate = Util.date.format(new Date(), 'yyyy-MM-dd');
		$('#startTime').datebox('setValue', cdate);
		$('#endTime').datebox('setValue', cdate);
		
		$(":radio").click(function(){
			var radioValue = $(this).val();
			pubFunction.setTime(radioValue);
	    });
		
		// 执行查询
		$('#queryBtn').off('click').on('click', onQuery);
		// 执行导出
		$('#exportBtn').on('click', easyuiExportToExcel);
		// 执行退出
		$('#closeBtn').on('click', pubFunction.CloseWebPage);
		// 执行打印
		$('#printBtn').on('click', pubFunction.PrintPage);
		//区域树状
		getArea();
		$('#areaTree').on('click',areaTree);
		$('#areaButton').on('click',areaButton);
		//清除店铺输入框  
		$('#shopTd').on('change',clearShop);
		//$('#shopTd').on('click',clearShop);
		//商品类型树状  
		goodsTypeTd();
		$('#goodsTypeTd').on('click',goodsTypeWin);
		$('#goodsTypeButton').on('click',goodsTypeButton);
		//清除品牌输入 
		$('#brandTd').on('change',clearBrand);
		//$('#brandTd').on('click',clearBrand);
		//清楚供应商
		$('#tdSupplier').on('change',supplierChange);
		//$('#tdSupplier').on('click',supplierChange);

	});
	//时间格式化
	function jsonTimeStamp(milliseconds) {
	    if (milliseconds != "" && milliseconds != null && milliseconds != "null") {
	        var datetime = new Date();
	        datetime.setTime(milliseconds);
	        var year = datetime.getFullYear();
	        var month = datetime.getMonth() + 1 < 10 ? "0"
	                + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
	        var date = datetime.getDate() < 10 ? "0" + datetime.getDate()
	                : datetime.getDate();
	        var hour = datetime.getHours() < 10 ? "0" + datetime.getHours()
	                : datetime.getHours();
	        var minute = datetime.getMinutes() < 10 ? "0"
	                + datetime.getMinutes() : datetime.getMinutes();
	        var second = datetime.getSeconds() < 10 ? "0"
	                + datetime.getSeconds() : datetime.getSeconds();
	        return year + "-" + month + "-" + date + " " + hour + ":" + minute
	                + ":" + second;
	    } else {
	        return "";
	    }
	 
	}

    function compute() {
        var rows = $("#dg").datagrid("getRows")//获取当前的数据行
        //计算总和
        var rtotal = 0, hctotal = 0, wftotal = 0, zgwctotal = 0, 
        	rtl_price1 = 0, rtl_price = 0, cst_price = 0, is_heji = 0, benefit_amt = 0, operatorTimeMap = {};
        for (var i = 0; i < rows.length; i++) {
        	var dateStr = jsonTimeStamp(rows[i]['OPERATOR_TIME']["time"]);
        	if(operatorTimeMap.hasOwnProperty(dateStr)){
        		var ic = operatorTimeMap[dateStr];
        		var ics = ic.split("-");
        		operatorTimeMap[dateStr] = ics[0]+"-"+(parseInt(ics[1])+1);
        	}else{
        		operatorTimeMap[dateStr] = i+"-"+1;
        	}
        	rtl_price1 += parseFloat(rows[i]['RTL_PRICE']);
            rtotal += parseFloat(rows[i]['QUANTITY']);
            hctotal += parseFloat(rows[i]['SALES_AMOUNT']);
            rtl_price += parseFloat(rows[i]['RTL_PRICE']);
            wftotal += parseFloat(rows[i]['RTL_PRICE_AMOUNT']);  
            cst_price += parseFloat(rows[i]['CST_PRICE']);
            zgwctotal += parseFloat(rows[i]['CST_PRICE_AMOUNT']);
            benefit_amt += parseFloat(rows[i]['BENEFIT_AMT']);

            if (rows[i]['areaname'] == "<b>合计：</b>") {
                is_heji = 1;
            }
        }
        var rowCount = 0;
        for(var k in operatorTimeMap){
        	rowCount ++;
        	var ic = operatorTimeMap[k];
			var ics = ic.split("-");
			$('#dg').datagrid('mergeCells',{
				index:ics[0],
				field:'_rn',
				rowspan:ics[1]
			}).datagrid('mergeCells',{
				index:ics[0],
				field:'OPERATOR_TIME',
				rowspan:ics[1]
			}).datagrid('mergeCells',{
				index:ics[0],
				field:'ORDER_ID',
				rowspan:ics[1]
			}).datagrid('mergeCells',{
				index:ics[0],
				field:'OPERATOR_NAME',
				rowspan:ics[1]
			}).datagrid('mergeCells',{
				index:ics[0],
				field:'OPERATOR_ID',
				rowspan:ics[1]
			});
			$("[field='_rn']").eq(parseInt(ics[0])+1).find("div").html(ics[1])
        }
        if (is_heji == 0) {
        	//新增一行显示统计信息
            $("#dg").datagrid('appendRow', {
            	_rn: rowCount,
                RTL_PRICE: rtl_price1.toFixed(2), 
                QUANTITY: rtotal.toFixed(2), 
                SALES_AMOUNT: hctotal.toFixed(2),
                RTL_PRICE:rtl_price.toFixed(2),
                RTL_PRICE_AMOUNT:wftotal.toFixed(2),
                CST_PRICE:cst_price.toFixed(2),
                CST_PRICE_AMOUNT:zgwctotal.toFixed(2),
                BENEFIT_AMT:benefit_amt.toFixed(2),
                
            }).datagrid('freezeRow',rows.length-1);
        }
    }
})(jQuery, window, document);
